package cn.jiedh.app.meiweidk;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;
import com.znsb.mxk.download.AppVersionUpdateHandler;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.CustomViewPager;
import cn.jiedh.app.meiweidk.Utils.UI.FirstGGDialog;
import cn.jiedh.app.meiweidk.Utils.UI.MyFragmentPagerAdapter;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.event.Observers;
import cn.jiedh.app.meiweidk.Utils.interfaces.FirstGGcallback;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.TimeUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.community.CommunityFragment;
import cn.jiedh.app.meiweidk.entity.ApplicationInfoBean;
import cn.jiedh.app.meiweidk.entity.IndexPopBean;
import cn.jiedh.app.meiweidk.entity.UpdateBean;
import cn.jiedh.app.meiweidk.homepage.FragmentHome;
import cn.jiedh.app.meiweidk.homepage.NetworkConnectChangedReceiver;
import cn.jiedh.app.meiweidk.homepage.NewProductData;
import cn.jiedh.app.meiweidk.loan.FragmentLoan;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.mine.FragmentMy;
import cn.jiedh.app.meiweidk.mine.PersonInfo;
import cn.jiedh.app.meiweidk.mine.PersonalDataActivity;
import cn.jiedh.app.meiweidk.network.GlideCircleTransform;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsManager;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsResultAction;
import cn.jiedh.app.meiweidk.strategy.StrategyActivity;
import cn.jiedh.app.meiweidk.welcome.AdverBean;

public class MainActivity extends BaseActivity implements Observers {
    MyFragmentPagerAdapter fragmentPagerAdapter;
    private ArrayList<Fragment> fragmentArrayList;

    private FragmentHome homeFragment;
    private FragmentLoan loanFragment;
    //    private FragmentStrategy strategyfragment;
    private CommunityFragment communityFragment;
    private FragmentMy myfragment;
    private Button[] mTabs;

    private String currentPage = "";//当前页面
    private String targetName = "";//点击进入的页面


    @BindView(R.id.viewpager)
    CustomViewPager layoutFrame;
    AppVersionUpdateHandler appVersionUpdateHandler = new AppVersionUpdateHandler(this);
    int tag;
    private NetworkConnectChangedReceiver mNetworkChangeListener;

    FirstGGDialog firstGGDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventUtils.getDefault().register(this);
        Bundle b = getIntent().getExtras();


        if (b != null) {
            tag = b.getInt("page");
            if (tag == 1) { //广告
                Bundle bundle = new Bundle();
                AdverBean adverBean = (AdverBean) b.getSerializable("adver");
                bundle.putString("title", adverBean.getName());
                bundle.putString("url", adverBean.getLink());
                ActivityUtil.next(this, MyWebActivity.class, bundle);
            } else if (tag == 2) { //h5
                String page = SPUtils.h52appgetpage();
                if (!page.isEmpty()) {
                    move2page(page);
                }
            }
            collect("20",null,null);
        }

        //如果没有用户信息就请求并且保存
        if (StringUtil.isEmpty(SPUtils.getValue(ConfigUtils.USER_IDCARD))) {
            getPersonData();
        }

    }

    private void move2page(String page) {
        switch (page) {
            case "index": //打开首页
                setButtonCheck(0);
                break;
            case "prodList": //打开产品列表
                setButtonCheck(1);
                break;
            case "prodDetail": //打开产品详情
                String pid = SPUtils.getpid();
                if (!TextUtils.isEmpty(pid)) {
                    Bundle b = new Bundle();
                    b.putInt("productId", Integer.parseInt(pid));
                    ActivityUtil.next(activity, LoanDetailActivity.class, b);
                }
                break;
            case "raidersList": //打开攻略列表
                setButtonCheck(2);
                break;
            case "raidersDetail": //打开攻略详情
                String rid = SPUtils.getrid();
                if (!TextUtils.isEmpty(rid)) {
                    Bundle b = new Bundle();
                    b.putInt("raidersId", Integer.parseInt(rid));
                    ActivityUtil.next(activity, StrategyActivity.class, b);
                }
                break;
        }
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_main;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle b = intent.getExtras();
        if (intent.getExtras() != null) {
            boolean isGoLoanList = b.getBoolean("isGoLoanList");
            boolean isHome = b.getBoolean("isHome");
            int tag = b.getInt("page");
            if (tag == 2) {  //h5
                String page = SPUtils.h52appgetpage();
                if (!page.isEmpty()) {
                    move2page(page);
                }
            } else {
                if (isGoLoanList) {
                    setButtonCheck(1);
                }
                if (isHome) {
                    setButtonCheck(0);
                }
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        System.out.println("onWindowFocusChanged--hasFocus---->" + hasFocus);
        if (hasFocus) {
//            layoutFrame.setOffscreenPageLimit(fragmentArrayList.size());
        }
    }

    @Override
    protected void initView(View view) {
        fragmentArrayList = new ArrayList<>();
        homeFragment = new FragmentHome();
        loanFragment = new FragmentLoan();
        communityFragment = new CommunityFragment();
        myfragment = new FragmentMy();
        fragmentArrayList.add(homeFragment);
        fragmentArrayList.add(loanFragment);
        fragmentArrayList.add(communityFragment);
        fragmentArrayList.add(myfragment);
        fragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentArrayList);
        layoutFrame.setAdapter(fragmentPagerAdapter);
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btn_home);
        mTabs[1] = (Button) findViewById(R.id.btn_loan);
        mTabs[2] = (Button) findViewById(R.id.btn_strategy);
        mTabs[3] = (Button) findViewById(R.id.btn_my);
        mTabs[0].setSelected(true);


    }

    @Override
    protected void initData() {
        mNetworkChangeListener = new NetworkConnectChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        registerReceiver(mNetworkChangeListener, filter);
        mNetworkChangeListener.setOnReceiver(isReceiver -> {
            if (isReceiver) {
                checkUpdate();
            }
        });
        layoutFrame.setOffscreenPageLimit(fragmentArrayList.size());
        //使用该监听会导致重复两次切换页面
//        layoutFrame.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                int currentItem = layoutFrame.getCurrentItem();
//                setButtonCheck(currentItem);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//            }
//        });
//        if (!(!SPUtils.getTime().isEmpty() && SPUtils.getTime().equals(TimeUtils.MillisToDayStr(System.currentTimeMillis())))) {
        getMyApplicationInfo();
//        }
        ApplicationInfoBean bean = SPUtils.getAppInfoFromSP();
        SPUtils.saveToApp(this, "dialogNum", bean.getBombBoxNum());
        //获取首页弹窗
        getGGInfo();
    }


    /**
     * 根据显示的页面给按钮设置选中
     *
     * @param currentItem
     */
    private void setButtonCheck(int currentItem) {
        for (int i = 0; i < mTabs.length; i++) {
            if (mTabs[i].isSelected()) {
                switch (i) {
                    case 0:
                        currentPage = "热门";
                        break;
                    case 1:
                        currentPage = "贷款大全";
                        break;
                    case 2:
                        currentPage = "社区";
                        break;
                    case 3:
                        currentPage = "我的";
                        break;
                }
            }
        }
        mTabs[0].setSelected(false);
        mTabs[1].setSelected(false);
        mTabs[2].setSelected(false);
        mTabs[3].setSelected(false);
        switch (currentItem) {
            case 0:
                MobclickAgent.onEvent(activity, "menu_hot_click");
                targetName = "底部菜单热门点击";
                mTabs[0].setSelected(true);
                break;
            case 1:
                MobclickAgent.onEvent(activity, "menu_loan_click");
                targetName = "底部菜单贷款大全点击";
                mTabs[1].setSelected(true);
                break;
            case 2:
                MobclickAgent.onEvent(activity, "menu_community_click");
                targetName = "底部菜单社区点击";
                mTabs[2].setSelected(true);
                break;
            case 3:
                MobclickAgent.onEvent(activity, "menu_my_click");
                targetName = "底部菜单我的点击";
                mTabs[3].setSelected(true);
                break;
            default:
                break;
        }
        SPUtils.saveBuried("click", "0", targetName, "",
            currentPage, "", "", "");
        layoutFrame.setCurrentItem(currentItem);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabClicked(View view) {
        int currentItem = 0;
        switch (view.getId()) {
            case R.id.btn_home:
                currentItem = 0;
                collect("2",null,null);
                break;
            case R.id.btn_loan:
                currentItem = 1;
                collect("3",null,null);
                break;
            case R.id.btn_strategy:
                currentItem = 2;
                collect("5",null,null);
                break;
            case R.id.btn_my:
                currentItem = 3;
                collect("1",null,null);
                break;
            default:
                break;
        }
        setButtonCheck(currentItem);
    }

    /**
     * 连点退出
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                T.showShort("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                try {
                    ApplicationInfoBean bean = SPUtils.getAppInfoFromSP();
                    SPUtils.saveToApp(this, "dialogNum", bean.getBombBoxNum());
                    finish();
                } catch (RuntimeException e) {
                }
            }
        }
        return false;
    }


    /**
     * 获取广告信息
     */
    void getGGInfo() {
        Map map = new HashMap<String, Objects>();
        request(this, UrlUtils.INDEX_POP, map, false, new ResponseSuccess<IndexPopBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<IndexPopBean> response) {
                if (response.getCode() == 0) {//允许弹窗
                    firstGGDialog = new FirstGGDialog(MainActivity.this, response.getData());
                    firstGGDialog.setCallback(new FirstGGcallback() {
                        @Override
                        public void onFirstClick() {
                            if(response.getData().getLinkType()==2){
                                apply(response.getData().getProductId());
                            }else{
                                Bundle bundle = new Bundle();
                                bundle.putString("title", "详情");
                                bundle.putString("url", response.getData().getLink());
                                ActivityUtil.next(MainActivity.this, MyWebActivity.class, bundle);
                                collect("21",null,response.getData().getLink());
                            }
                        }
                    });
                    firstGGDialog.show();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("首页弹窗错误" + msg);
//                T.showShortToast(msg);
            }
        });
    }

    /**
     * 应用基本信息
     */
    void getMyApplicationInfo() {
        Map map = new HashMap<String, Objects>();
        request(this, UrlUtils.GETAPPLICATIONINFO, map, false, new ResponseSuccess<ApplicationInfoBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ApplicationInfoBean> response) {
                if (response.getCode() == 0) {//成功
                    SPUtils.saveToApp(MainActivity.this, ConfigUtils.SHOW_TIME, TimeUtils.MillisToDayStr(System.currentTimeMillis()));
                    SPUtils.saveAppInfoToSP(response.getData());
                    L.i("应用基本信息 ： " + response.getData().toString());
                    SPUtils.getAppInfoFromSP();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("应用基本信息错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    /**
     * 版本更新
     */
    void checkUpdate() {
        Map map = new HashMap<String, Objects>();
        request(this, UrlUtils.UPDATEAPP, map, false, new ResponseSuccess<UpdateBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<UpdateBean> response) {
                if (response.getCode() == 2) {//有更新
                    UpdateBean updateBean = response.getData();
                    if ("0".equals(updateBean.getType())) {//	是否强制更新 0否 1是
                        new AlertDialog(MainActivity.this).builder().setTitle("有版本更新啦").setMsg(updateBean.getUpdateContent()).setCancelable(true).setNegativeButton(getResources().getString(R.string.ignore), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                            }
                        }).setPositiveButton(getResources().getString(R.string.upgrade_now), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                toUpdate(updateBean);
                            }
                        }).show();
                    } else {//强制更新
                        new AlertDialog(MainActivity.this).builder().setTitle("有版本更新啦").setMsg(updateBean.getUpdateContent()).setCancelable(false).setPositiveButton(getResources().getString(R.string.upgrade_now), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                toUpdate(updateBean);
                            }
                        }, false).show();
                    }
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("应用基本信息错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    /**
     * 去更新app
     *
     * @param updateBean
     */
    private void toUpdate(UpdateBean updateBean) {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                appVersionUpdateHandler.startUpdate(updateBean.getUrl(), Integer.valueOf(updateBean.getInEdition()));
            }

            @Override
            public void onDenied(String permission) {
                T.showShortToast("没有获取存储卡读写权限");
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventUtils.getDefault().unregister(this);
        unregisterReceiver(mNetworkChangeListener);
    }

    @Override
    public void update(Object obj) {
        if (obj instanceof EventScreen) {
            EventScreen eventScreen = (EventScreen) obj;
            if (eventScreen.getType().equals("gowebactivity")) {
                L.d("进入首页3-------", "==========================");
                setButtonCheck(2);
            }
        }
    }


    /**
     * 获取用户信息
     */
    private void getPersonData() {
        Map<String, Object> args = new HashMap<>();
        args.put("phone", SPUtils.getPhone());
        request(this, UrlUtils.GET_PERSONAL_INFO, args, true, new ResponseSuccess<PersonInfo>() {
            @Override
            public void onRequestSucceed(BaseResponse<PersonInfo> response) {
                PersonInfo infor = response.getData();

                if (response.isSuccess()) {

                    SPUtils.saveUserData(infor);

                }
            }
        });
    }


    /**
     * 统计并跳转
     *
     * @param productId
     */
    private void apply(int productId) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.ADDBROWSE, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {

                } else {
                    T.showShort(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }


    /**
     * 功能统计
     *
     * @param type      类型
     * @param collectId type为0和19时collectId不为空
     * @param url       有就传
     */
    private void collect(String type, String collectId, String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        if (null != collectId) {
            map.put("collectId", collectId);
        }
        if (null != url) {
            map.put("url", url);
        }
        request(UrlUtils.COLLECT, map, true, new ResponseSuccess<NewProductData>() {
            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
            }
        });
    }
}
